<template>
  <view>
    <!-- 1.0 收货地址 -->
    <view
      class="address"
      @tap="getAddressHandle"
    >
      <!-- 1.1 情况1：收货地址 -->
      <view
        class="address_info"
        v-if="address.userName"
      >
        <!-- text  -->
        <text
          class="address_detail"
          user-select
        >
          {{ addressDetail }}
        </text>
        <view class="address_bottom">
          <text class="address_bottom_text">{{ address.userName }}</text>
          <text class="address_bottom_text">{{ address.telNumber }}</text>
        </view>
      </view>
      <!-- 1.2 情况2： 空状态 -->
      <view
        class="address_empty"
        v-else
      >
        <view class="address_empty_button">
          点击获取收货地址
        </view>
      </view>
    </view>
    <!-- 2.0 结算商品列表 -->
    <view class="goods_list">
      <view class="goods_list_title">已选商品</view>
      <!-- 小程序的 block 空标签，类似于 vue 中的 template  -->
      <view
        v-for="item in cartList"
        :key="item.goods_id"
        class="goods_item"
      >
        <GoodsItem
          v-if="item.goods_selected"
          :item="item"
        >
          <view class="goods_item_count">x{{ item.goods_count }}</view>
        </GoodsItem>
      </view>
    </view>
    <!-- 3.0 底部栏 -->
    <view class="bottom">
      <text class="total_text">合计：</text>
      <text class="total_price price">{{totalPrice}}</text>
      <view
        @tap="payHandle"
        class="account"
      >去支付({{account}})</view>
    </view>
  </view>
</template>

<script>
// 导入组件
import GoodsItem from "@/components/GoodsItem/index.vue";
import { checkOrder, getPayParams, ordersCreate } from "@/api";
export default {
  // 注册组件
  components: {
    GoodsItem,
  },
  data() {
    return {
      address: {},
      cartList: [],
    };
  },
  // 计算属性 - 如果要计算出一个新的变量，用计算属性
  computed: {
    // 计算出详细地址
    addressDetail() {
      const { provinceName, cityName, countyName, detailInfo } = this.address;
      return provinceName + cityName + countyName + detailInfo;
    },
    // 商品总价的计算
    totalPrice() {
      let totalPrice = 0;
      this.cartList.forEach((item) => {
        if (item.goods_selected) {
          totalPrice += item.goods_price * item.goods_count;
        }
      });
      return totalPrice;
    },
    // 计算结算个数
    account() {
      let account = 0;
      this.cartList.forEach((item) => {
        if (item.goods_selected) {
          account += item.goods_count;
        }
      });
      return account;
    },
  },
  onLoad() {
    this.address = uni.getStorageSync("address") || {};
    this.cartList = uni.getStorageSync("cartList") || [];
  },
  methods: {
    // 获取收货地址
    getAddressHandle() {
      // 获取用户收货地址。调起用户编辑收货地址原生界面。
      /* #ifdef MP-WEIXIN */
      uni.chooseAddress({
        success: (res) => {
          console.log(res); // 编辑完成后返回用户选择的地址
          // 绑定到 data 中用于界面渲染
          this.address = res;
          // 保存到本地存储
          uni.setStorageSync("address", res);
        },
      });
      /* #endif */
      //  ifndef      if not defind    排除某些平台
      /* #ifndef MP-WEIXIN || MP-TOUTIAO || MP-BAIDU || MP-ALIPAY */
      uni.showToast({
        title: "功能升级中...",
        icon: "none",
        duration: 1000,
      });
      /* #endif */
    },
    async payHandle() {
      console.log("微信支付流程开始");
      // 订单数据
      const goods = this.cartList
        // 过滤出选中的商品
        .filter((item) => item.goods_selected)
        // 映射成后端所需的参数格式
        .map((item) => {
          return {
            goods_id: item.goods_id,
            goods_number: item.goods_count,
            goods_price: item.goods_price,
          };
        });
      try {
        // 支付流程1：创建订单，返回订单号
        const { order_number } = (
          await ordersCreate({
            order_price: this.totalPrice,
            consignee_addr: this.addressDetail,
            goods: goods,
          })
        ).data.message;
        // 支付流程2：根据订单号，让后端生成微信支付所需的参数
        const { pay } = (await getPayParams({ order_number })).data.message;
        // console.log(pay);
        // 支付流程3：调用微信支付，使用后端返回参数作为支付参数
        await wx.requestPayment(pay);
        // 支付流程4：支付结束，后端需要掉接口检查订单的支付状态
        await checkOrder({ order_number });
        // 给用户一个支付成功的提示
        uni.showToast({
          title: "支付成功",
          duration: 1000,
        });
        // 支付完成后，删除本地存储的数据(把没选中的商品重新保存一下到本地)
        const cartList = this.cartList.filter((item) => !item.goods_selected);
        uni.setStorageSync("cartList", cartList);
        // 跳转到订单页面 - redirectTo 相当于 Vue 的 replace 替换页面
        uni.redirectTo({ url: "/pages/order/main" });
      } catch (error) {
        uni.showToast({
          title: "支付失败",
          icon: "none",
          duration: 1000,
        });
      }
    },
  },
};
</script>

<style lang="less">
page {
  background-color: #f9f9f9;
}
.address {
  height: 188rpx;
  margin: 20rpx;
  background-color: #fff;
  border-radius: 5rpx;
  .address_empty {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    .address_empty_button {
      width: 300rpx;
      height: 90rpx;
      border-radius: 45rpx;
      border: 1rpx solid var(--mainColor);
      font-size: 30rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      color: var(--mainColor);
    }
  }

  .address_info {
    padding: 20rpx;
    .address_detail {
      font-size: 32rpx;
    }

    .address_bottom {
      margin-top: 20rpx;
      font-size: 26rpx;
      .address_bottom_text {
        margin-right: 30rpx;
      }
    }
  }
}
.goods_list {
  margin: 20rpx;
  background-color: #fff;
  border-radius: 5rpx;
  .goods_list_title {
    height: 88rpx;
    padding: 0 20rpx;
    display: flex;
    align-items: center;
  }
  .goods_item {
    position: relative;
    .goods_item_count {
      position: absolute;
      right: 20rpx;
      bottom: 20rpx;
    }
  }
}
.bottom {
  height: 88rpx;
  display: flex;
  align-items: center;
  padding: 0 20rpx;
  position: fixed;
  // 同时设置左右，可以拉伸出宽度
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #fff;
  border-top: 1rpx solid #ddd;
  .select_text {
    font-size: 22rpx;
    color: #999;
    margin-left: 10rpx;
  }
  .total_text {
    font-size: 26rpx;
    margin-left: 20rpx;
  }
  .price {
    font-size: 36rpx;
    flex: 1;
  }
  .account {
    width: 150rpx;
    height: 52rpx;
    background-color: var(--mainColor);
    color: #fff;
    border-radius: 30rpx;
    font-size: 22rpx;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>